package org.kzwl.service.app.impl;

import cn.hutool.core.util.IdcardUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang3.StringUtils;
import org.kzwl.comm.advice.BizException;
import org.kzwl.comm.advice.Consts;
import org.kzwl.comm.pojo.ResponseData;
import org.kzwl.comm.pojo.bo.*;
import org.kzwl.comm.pojo.bo.user.UpdateUserBO;
import org.kzwl.comm.pojo.dto.UserLoginDTO;
import org.kzwl.comm.pojo.dto.user.UserTokenDTO;
import org.kzwl.comm.utils.MyUtils;
import org.kzwl.entity.app.CuLive;
import org.kzwl.entity.app.Setting;
import org.kzwl.entity.app.User;
import org.kzwl.entity.app.Verification;
import org.kzwl.mapper.app.LiveMapper;
import org.kzwl.mapper.app.UserMapper;
import org.kzwl.service.app.SettingService;
import org.kzwl.service.app.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.kzwl.service.app.VerificationService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 张国伟/郭家恒
 * @since 2020-09-10
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private VerificationService verificationService;

    @Autowired
    SettingService settingService;

    @Autowired
    private LiveMapper liveMapper;

    @Override
    public ResponseData<IPage<User>> IsLiveQuery(IsUserLiveBO isUserLiveBO) {
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.like(!"".equals(isUserLiveBO.getCuUsername()), User::getCuUsername, isUserLiveBO.getCuUsername());
        Page<User> userPage = this.baseMapper.selectPage(new Page<>(isUserLiveBO.getCurrent(), isUserLiveBO.getSize()), lambdaQueryWrapper);

        if (userPage.getRecords().size() > 0) {
            userPage.getRecords().forEach(item -> {
                item.setCuUserPassword(null);
            });
        }
        return new ResponseData<>(userPage);
    }

    @Override
    public ResponseData<Void> updateIsLive(IsUserLiveUpadteBO isUserLiveUpadteBO) {
        User user = new User();
        BeanUtils.copyProperties(isUserLiveUpadteBO, user);
        this.updateById(user);
        if (ObjectUtil.isNotNull(isUserLiveUpadteBO.getCuUserIsLive()))
        {
            if (isUserLiveUpadteBO.getCuUserIsLive() == 1) {
                //暂时去掉增加直播间的逻辑
                //            CuLive live= new CuLive();
//            live.setCuLiveAppName(UUID.randomUUID().toString());
//            live.setCuLiveStreamName(UUID.randomUUID().toString());
//            live.setCuUserId(isUserLiveUpadteBO.getCuUserId());
//            live.setCuLiveTitle("空直播间");
//            liveMapper.insert(live);
            } else {
                QueryWrapper<CuLive> queryWrapper = new QueryWrapper<>();
                queryWrapper.lambda().eq(CuLive::getCuUserId, isUserLiveUpadteBO.getCuUserId());
                liveMapper.delete(queryWrapper);
            }
        }

        return new ResponseData<>();
    }

    //region 用户登录
    @Override
    public UserLoginDTO userLogin(UserLoginBO bo) {

        QueryWrapper<User> queryWrapper = new QueryWrapper<>();

        queryWrapper.lambda().eq(User::getCuUserPhone, bo.getCuUserPhone());
        User user = userMapper.selectOne(queryWrapper);
        if (user == null) {
            throw new BizException("账号不存在");
        }

        //密码登录
        if (bo.getCuUserLoginType().equals(0)) {

            if (!user.getCuUserPassword().equals(MyUtils.createMd5(bo.getCuUserPassword()))) {
                throw new BizException(" 账号或密码错误");
            }

            //手机号登录
        } else if (bo.getCuUserLoginType().equals(1)) {
            Verification code = verificationService.getCode(bo.getCuUserPhone());
            if (!code.getCuVerificationCode().equals(bo.getCuVerificationCode())) {
                throw new BizException("验证码过期或错误");
            }

            verificationService.updateCode(bo.getCuUserPhone(), bo.getCuVerificationCode());
        } else if (bo.getCuUserLoginType().equals(2)) {

        }

        String jwt = MyUtils.createJwt(JSON.toJSONString(user));
        UserLoginDTO dto = new UserLoginDTO();
        dto.setJwt(jwt);
        return dto;
    }
    //endregion

    //region 注册
    @Override
    public void register(UserLoginBO bo) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(User::getCuUserPhone, bo.getCuUserPhone());
        User user = userMapper.selectOne(queryWrapper);
        if (user != null) {
            throw new BizException("手机号已注册,请登录");
        }
        Verification code = verificationService.getCode(bo.getCuUserPhone());
        if (!code.getCuVerificationCode().equals(bo.getCuVerificationCode())) {
            throw new BizException("验证码过期或错误");
        }
        user = new User();
        user.setCuUsername(bo.getCuUserPhone());
        user.setCuUserPassword(MyUtils.createMd5(bo.getCuUserPassword()));
        user.setCuUserPhone(bo.getCuUserPhone());
        user.setCuUserImage("https://repair-java.oss-cn-beijing.aliyuncs.com/images/1588467392513.jpg");
        userMapper.insert(user);
    }
    //endregion

    //region 根据token获取用户信息
    @Override
    public UserTokenDTO getUserByToken(UserLoginDTO bo) {
        Integer userId = MyUtils.getUserId(bo.getJwt());
        User user = userMapper.selectById(userId);
        if (user == null) {
            throw new BizException("用户信息有误");
        }

        //如果没有最后一次的日期，也就是第一次看书
        if (user.getCuUserMinuteLast() == null) {

        } else {
            //否则，开始判断上一次读书是啥时候
            //时间紧，暂时如此处理。
            String last = user.getCuUserMinuteLast().toString();
            String t = last.substring(0, last.indexOf("T"));
            String s = LocalDateTime.now().toString();
            s = last.substring(0, s.indexOf("T"));
            //如果不是同一天
            if (!s.equals(t)) {
                //清空今日读书时长
                User upd = new User();
                upd.setCuUserId(userId);
                upd.setCuUserDayMinute(0);
                userMapper.updateById(upd);
                user.setCuUserDayMinute(0);
            }
        }

        UserTokenDTO dto = new UserTokenDTO();
        BeanUtils.copyProperties(user, dto);

//        //region 查询基本设置
//        List<String> settingNames = new ArrayList<String>(){{
//            add("SettingBookBanner");//轮播图
//        }};
//        Setting setting = settingService.queryBasic(settingNames).get(0);
//        dto.getBanners().addAll(Arrays.asList(setting.getCuSettingValue().split("\\|")));
//        //endregion
        return dto;
    }
    //endregion

    //region 发送短信
    @Override
    public void sendSms(UserLoginBO bo) {
        Integer randomCode = MyUtils.getRandomCode();
        MyUtils.sendSms(bo.getCuUserPhone(), "{\"code\":\"" + randomCode + "\"}", Consts.AliYun.SMSTEMPLATECODE);
        verificationService.insetCode(bo.getCuUserPhone(), randomCode.toString());
    }

    @Override
    public User WebLogin(WebUserLoginBO webUserLoginBO) {
        if (webUserLoginBO.getCuUsername() == null || "".equals(webUserLoginBO.getCuUsername())) {
            throw new BizException("用户名不能为空");
        }

        if (webUserLoginBO.getCuUserPassword() == null || "".equals(webUserLoginBO.getCuUserPassword())) {
            throw new BizException("密码不能为空");
        }
        User selectOne = this.baseMapper.selectOne(new QueryWrapper<User>().lambda().eq(User::getCuUsername, webUserLoginBO.getCuUsername()));
        if (selectOne != null) {
            if (selectOne.getCuUserPassword().equals(MyUtils.createMd5(webUserLoginBO.getCuUserPassword()))) {
                selectOne.setCuUserPassword("");
                userMapper.syncLoginInfo(selectOne.getCuUserId(),LocalDateTime.now());
                return selectOne;
            } else {
                throw new BizException("密码不正确");
            }
        } else {
            throw new BizException("用户名不存在");
        }

    }

    @Override
    public ResponseData<Void> useRegister(UseRegisterBO useRegisterBO) {
        User selectById = this.baseMapper.selectOne(new QueryWrapper<User>().lambda().eq(User::getCuUserPhone, useRegisterBO.getCuUserPhone()));
        if (selectById != null) {
            throw new BizException("手机号已经存在");
        }

        User selectById2 = this.baseMapper.selectOne(new QueryWrapper<User>().lambda().eq(User::getCuUsername, useRegisterBO.getCuUsername()));
        if (selectById2 != null) {
            throw new BizException("用户名已存在");
        }
        if (useRegisterBO.getCuUsername() == null || useRegisterBO.getCuUsername().equals("")) {
            throw new BizException("用户名不能为空");
        }
        if (useRegisterBO.getCuUserPassword() == null || useRegisterBO.getCuUserPassword().equals("")) {
            throw new BizException("密码不能为空");
        }
        if (useRegisterBO.getCuUserPhone() == null || useRegisterBO.getCuUserPhone().equals("")) {
            throw new BizException("手机号不能为空");
        }

//        boolean validCard = IdcardUtil.isValidCard(useRegisterBO.getCuUserPhone());
//        if (!validCard){
//            throw new BizException("手机号不合法");
//        }
        User user = new User();
        user.setCuUsername(useRegisterBO.getCuUsername());
        user.setCuUserPhone(useRegisterBO.getCuUserPhone());
        user.setCuUserPassword(MyUtils.createMd5(useRegisterBO.getCuUserPassword()));
        user.setCuUserImage("https://repair-java.oss-cn-beijing.aliyuncs.com/images/1588467392513.jpg");
        this.userMapper.insert(user);
        return new ResponseData<>();
    }

    //region PC用户修改个人信息
    @Override
    public void updateUser(UpdateUserBO bo) {
        User user = userMapper.selectById(bo.getCuUserId());
        if (user == null){
            throw new BizException("未找到用户信息");
        }

        User update = new User();
        BeanUtils.copyProperties(bo,update);
        if (bo.getCuUserPassword() != null && !bo.getCuUserPassword().equals("")) {
            String md5 = MyUtils.createMd5(bo.getCuUserPassword());
            if (!md5.equals(user.getCuUserPassword())){
                throw new BizException("密码错误");
            }
            update.setCuUserPassword(MyUtils.createMd5(bo.getNewCuUserPassword()));
        }else{
            update.setCuUserPassword(null);
        }

        userMapper.updateById(update);

    }
    //endregion


    @Override
    public Integer userCount() {
        int i = userMapper.userCount();
        return i;
    }
}
